<template>
  <div>
       <el-table :data="tableData"  @row-click='handleCurrentChanges' style="width: 100%"  highlight-current-row>
      <el-table-column label="ID"  prop="index">
      </el-table-column>     
      <el-table-column  :label="$t('message.medias.dev')" >
        <template  slot-scope="scope">   
          <span>{{scope.row.devs }}</span>
        </template> 
      </el-table-column>
    </el-table>
    <setForm id="1" v-show="show">       
       <template slot="boxTop">{{$t('message.medias.channelSetting')}}</template>
          <template slot="boxMain">                
            <el-row>
            <el-col :span="4" class="col4">                          
                <p>{{$t('message.medias.dev')}}</p>                          
            </el-col>
            <el-col :span="20" class="span17">        
              <el-checkbox-group v-model="currentRow.devs"  :max="2">
                <el-checkbox v-for="option in devsToSelect" :label="option.value" :key="option.value">{{option.text}}</el-checkbox>
              </el-checkbox-group>
            </el-col>
          </el-row>
          <el-button  class="btnsave" @click="onSaveChannel" v-if="false">{{$t('message.save')}}</el-button>
          </template>
    </setForm>
    <setForm id="2" v-show="showVideo">       
       <template slot="boxTop">{{$t('message.medias.delaySetting')}}</template>
          <template slot="boxMain">                
            <el-row>
            <el-col :span="4" class="col4">                          
                <p>{{$t('message.medias.delayMethod')}}</p>                          
            </el-col>
            <el-col :span="20" class="span17"> 
              <el-radio-group v-model="isOn">
                <el-radio :label='false' >{{$t('message.medias.normalDelay')}}</el-radio>
                <el-radio :label='true' >{{$t('message.medias.lowDelay')}}</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
          <el-button  class="btnsave" @click="onSaveChannelDelay">{{$t('message.save')}}</el-button>
          </template>
    </setForm>
    <setForm id="3" v-show="showVideo">       
       <template slot="boxTop">{{$t('message.medias.subtitle')}}</template>
          <template slot="boxMain">  
            <el-table :data="subtitleData" style="width: 100%">
                <el-table-column
                  :label="$t('message.medias.enable')">
                  <template slot-scope="scope">
                    <span>{{scope.row.enable? $t('message.systems.enable'): $t('message.systems.disable')}}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  :label="$t('message.medias.fontsize')"
                  prop="fontSize">
                </el-table-column>
                <el-table-column :label="$t('message.medias.foregrounnd')">
                   <template slot-scope="scope">
                    <div :style="'width:60px;height:24px;border-style: solid;border-width:1px;border-color:#606266;background-color:' + scope.row.foreColor"></div>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('message.medias.content')">
                  <template slot-scope="scope">{{showContent(scope.row)}}</template>
                </el-table-column>
                <el-table-column :label="$t('message.medias.operation')">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      @click="editSubtitle(scope.$index, scope.row)">{{$t('message.medias.edit')}}</el-button>             
                  </template>
                </el-table-column>
              </el-table>  
          </template>
    </setForm>    
    <!-- 背景图 -->
    <setForm id="4" v-show="showVideo">       
       <template slot="boxTop">{{$t('message.medias.backgroundImg')}}</template>
          <template slot="boxMain">   
            <el-row>
            <el-col :span="12" class="col4">                            
                <img :src="imgFile" id="img" style="width:400px;height:auto;" >               
            </el-col>
            <el-col :span="12" class="col20">
              <el-checkbox v-model="bgEnable" @change="onBgEnableChanged">{{$t('message.medias.enable')}}</el-checkbox>  
              <el-upload              
                ref="upload"
                id="imgUploadFile"
                :limit="1"
                :multiple="false"
                action=""
                :before-upload="onFileChange"                
                :on-preview="handlePictureCardPreview"
                :on-exceed="onFilesOutOfMax"
                accept=".jpg"
                list-type="picture-card">
                <i class="el-icon-plus"></i>
              </el-upload>   
               <el-button  @click="uploadBgImg" style="margin-top:40px;">{{$t('message.save')}}</el-button>           
              </el-col>
          </el-row>
          </template>
    </setForm>
      <!-- 字幕弹窗 -->
     <el-dialog :title="$t('message.medias.subtitle')" :visible.sync="subtitleVisible"  width="660px" @open="onSubDialogOpen" id="subDialog">
      <canvas id="myCanvas" width="576;" height="324"></canvas>      
      <el-form label-position="right" label-width="80px" :model="subtitle" size="mini">  
        <el-form-item :label="$t('message.medias.enable')">
          <el-checkbox v-model="subtitle.enable" >{{$t('message.medias.enable')}}</el-checkbox>
        </el-form-item>
        <el-form-item :label="$t('message.medias.type')">
          <select v-model="subtitle.type" @change="onSubTypeChange">
            <option v-for="option in subtitleTyps" :key="option" :value="option">{{option}}</option>
          </select>
        </el-form-item>
        <el-form-item :label="$t('message.medias.fontsize')" >
          <el-input v-model="subtitle.fontSize" placeholder="" type="number"></el-input> 
        </el-form-item>
        <el-form-item :label="$t('message.medias.foregrounnd')">        
          <select v-model="subtitle.foreColor">
            <option v-for="option in colorOptions" :key="option.value" :value="option.value" >{{option.text}}</option>
          </select>
        </el-form-item>         
        <el-form-item :label="$t('message.medias.horizontal')">
          <el-slider v-model="subtitle.pos.x" ></el-slider>
        </el-form-item>         
        <el-form-item :label="$t('message.medias.vertical')">
          <el-slider v-model="subtitle.pos.y" ></el-slider>
        </el-form-item>         
        <el-form-item :label="$t('message.medias.content')" v-show="showSubContent">
          <el-input v-model="subtitle.content" placeholder="" ></el-input>
        </el-form-item>  
        <el-form-item>
        <el-button @click="subtitleVisible = false">{{$t('message.cancel')}}</el-button>
        <el-button  @click="onSaveSutitle">{{$t('message.ok')}}</el-button>
        </el-form-item>  
      </el-form>
    </el-dialog>     
    <!-- 图片预览弹窗 -->
    <el-dialog :visible.sync="dialogVisible" size="tiny">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
   
  </div>
</template>

<script>
import { api,getHostName  } from "../../../../libs/api";
import setForm from "@/components/setForm";
import mylist from "@/components/MyList";
import topTable from "@/components/topTable";
import ebus from "@/libs/ebus";
import { mapState } from "vuex";
import debugCfg from '../../../../libs/debugCfg';
import axios from 'axios';
export default {
  created() {
    ebus.emit("getOutputChannelInfo", this);
  },
  computed: {
    ...mapState(["media"]),
    ...mapState(["system"]),
    tableData() {
      var items = [];
      if (this.media.outputChannel.channels) {
        items = this.media.outputChannel.channels;
      }
      return items;
    },
    subtitleData1() {
      var items = [];
      if (this.currentRow.subtitle) {
        items = this.currentRow.subtitle;
      }      
      return items;
    },
    devsToSelect() {
      var items = [];
      var devs = this.media.outputDev.devs;
      
      if (devs) {
        for (var i = 0; i < devs.length; i++) {
          items.push({
            text: devs[i].name,
            value: i
          });
        }
      }      
      return items;
    }
  },
  watch:{
    subtitle: {
      handler: function(val, oldVal) {
        this.drawLayout();
      },
      deep: true
    }
  },
  data() {
    return {
      defaultUrl: '',
      showVideo:false,
      showBackGround: false,
      showSubContent: false,
      dialogVisible: false,
      file: null,
      dialogImageUrl: '',
      bgEnable: false,
      isOn: false,
      imgFile: 'http://' + getHostName() + ":8080/_resources/custom/background.jpg",
      labelPosition: 'right',
      formLabelAlign:{
        name: '',
        region: '',
        type: ''
      },
      subtitleVisible: false,
      subtitleData: [
        {
          index: 0,
          content: ""
        }
      ],
      currentRow: {},
      currentSubtitle: [],
      audioSupports: ["AAC", "G711A", "G711U", "G722"],
      videoSupports: ["H264", "H265"],
      subtitleIndex: 0,
      subtitle: {
        base:{
          h: 0,
          v: 0
        },
        pos:{
          x: 0,
          y: 0
        },
        fontSize: 20,
        foreColor: '#ffffff',
        enable: false,
        index: -1,
        content: '',
        type: ''
      },
      subtitleTyps: [
        "text",
        "ipaddr",
        "devName"
      ],
      show: false,
      index: 0,
      channel: {},
      devCnt: 2,
      capPerDec: 2,
      devs: [],
      dev: 1,
      enable: true,
      subtitletype: "",
      fontsize: 12,
      content: "example",
      foregrounnd: null,
      background: null,
      columns: [
        {
          label: "decCnt",
          prop: "decCnt"
        },
        {
          label:  "capPerDec",
          prop: "capPerDec"
        },
        {
          label: this.$t('message.medias.audioSupport'),
          prop: "audioSupport"
        },
        {
          label: this.$t('message.medias.videoSupport'),
          prop: "videoSupport"
        },
        {
          label: this.$t('message.medias.dev'),
          prop: "devs"
        }
      ],
      subtitlecolumns: [
        {
          label: "ID",
          prop: "index"
        },
        {
          label: "content",
          prop: "content"
        },
      ],
      colorOptions: [
        {
          value: "#000000",
          text: "black"
        },
        {
          value: "#ffffff",
          text: "white"
        },
        {
          value: "#0000ff",
          text: "blue"
        },
        {
          value: "#a52a2a",
          text: "brown"
        },
        {
          value: "#808080",
          text: "gray"
        },
        {
          value: "#008000",
          text: "green"
        },
        {
          value: "#ff0000",
          text: "red"
        },
        {
          value: "#ffff00",
          text: "yellow"
        },
        {
          value: "#1abc9c",
          text: "turquoise"
        },
        {
          value: "#2ecc71",
          text: "emerald"
        },
        {
          value: "#3498db",
          text: "peter river"
        },
        {
          value: "#9b59b6",
          text: "amethyst"
        },
        {
          value: "#34495e",
          text: "wet asphalt"
        },
        {
          value: "#16a085",
          text: "green sea"
        },
        {
          value: "#27ae60",
          text: "nephritis"
        },
        {
          value: "#2980b9",
          text: "belize hole"
        },
        {
          value: "#8e44ad",
          text: "wisteria"
        },
        {
          value: "#2c3e50",
          text: "midnight blue"
        },
        {
          value: "#f1c40f",
          text: "sun flower"
        },
        {
          value: "#e67e22",
          text: "carrot"
        },
        {
          value: "#e74c3c",
          text: "alizarin"
        },
        {
          value: "#ecf0f1",
          text: "clouds"
        },
        {
          value: "#95a5a6",
          text: "concrete"
        },
        {
          value: "#f39c12",
          text: "orange"
        },
        {
          value: "#d35400",
          text: "pumpkin"
        },
        {
          value: "#c0392b",
          text: "pomegranate"
        },
        {
          value: "#bdc3c7",
          text: "silver"
        },
        {
          value: "#7f8c8d",
          text: "asbestos"
        }
      ]
    };
  },
  components: {
    setForm,
    mylist,
    topTable
  },
  methods: {
    handleCurrentChanges(val) {   
      this.defaultUrl = val.imgFile;
      
      //需要把返回的路径替换掉前面的部分:tzns://default/pic/background1.jpg => http://{hostname}:{port}/_default/pic/background1.jpg
      if(val.imgFile && val.imgFile.includes('/default')) {
        this.imgFile = 'http://' + getHostName() + ":8080/_" + val.imgFile.substr(val.imgFile.indexOf('default'), val.imgFile.length - val.imgFile.indexOf('default'))
      } else if(val.imgFile && val.imgFile.includes('/resources')) {
        this.imgFile = 'http://' + getHostName() + ":8080/_" + val.imgFile.substr(val.imgFile.indexOf('resources'), val.imgFile.length - val.imgFile.indexOf('resources'))
      } else{
        this.imgFile = '';
      }     
      this.subtitleData = [];
      this.subtitleData = val.subtitle;
      this.currentRow = val;
      this.index = val.index;
      this.isOn = val.isOn;
      this.bgEnable = val.enable;      

      this.show = true;
      this.showBackGround = val.index == 2? false : true;
      this.showVideo = val.decCnt == 0 ? false: true;
      
    },
    onSaveChannel() {
      var option = {
        decCnt: this.currentRow.decCnt,
        devs: this.currentRow.devs,
        capPerDec: this.currentRow.capPerDec,
        audioSupport: this.currentRow.audioSupport,
        videoSupport: this.currentRow.videoSupport
      };      
      api.onRequest(
        "$method.$set.media.mo.ch" + this.currentRow.index,
        JSON.stringify(option),
        null,
        null,
        function(message, reqReply) {
          var res = JSON.parse(message)
          if (res.code == 0) {
            this.notification("Success", "");
          } else {
            this.showCodeMsg(res.code, this, res.msg);
          }
          ebus.emit("getOutputChannelInfo", this);
        }.bind(this)
      );
    },
    onSaveChannelDelay() {
      var option = {
        isOn: this.isOn
      };   
         
      api.onRequest("$method.$set.media.mo.ch" + this.currentRow.index + '.lowdelay', JSON.stringify(option) ).then(msg =>{
        var res = JSON.parse(msg)
        if(res && res.code == 0){
          this.notification("Success", "");
        } else{
          this.showCodeMsg(res.code, this, res.msg);
        }
        ebus.emit("getOutputChannelInfo", this);
      });
    },
    subtitleChange(val){
      this.currentSubtitle = val
    },
    getBgUrl(){
      api.onRequest( "$method.$get.media.mo.ch" + this.index + ".background", null, null, null, function(msg2, reply) {
          var resData = JSON.parse(msg2)
          if(resData.code == 0){  
            this.defaultUrl = resData.data.imgFile
            this.imgFile = 'http://' + getHostName() + ":8080/_" + resData.data.imgFile.substr(resData.data.imgFile.indexOf('default'), resData.data.imgFile.length -resData.data.imgFile.indexOf('default')) + '?' + Math.random()
          }
        }.bind(this)
      );
    },
    uploadBgImg() {     
      if (!this.file) {
        return;
      }
      var url = "$method.getUploadUrl.sys.netStorage.share0.info"; //暂时写死，以后不一定只有一个目录
      var option = {
        fileType: "pic",
        fileName: 'background' + this.index +'.jpg',
        fileSize: this.file.size
      };
      option = JSON.stringify(option);
      api.onRequest(url, option, null, null, function(msg, reply) {
          var res = JSON.parse(msg);                    
          if (res.code == 0) {                        
            var xhr = new XMLHttpRequest();  
            var url = "http://" + getHostName() + ":8080/_default" + res.data.url.substring(res.data.url.indexOf('default') + 7)
            xhr.open("PUT", url, true);      
            xhr.onload = (e) => {
              var opt = {
                enable: this.bgEnable,
                imgFile: res.data.url
              };
              api.onRequest( "$method.$set.media.mo.ch" + this.index + ".background", JSON.stringify(opt), null, null, function(msg2, reply) {
                  var resData = JSON.parse(msg2)
                  if(resData.code == 0){   
                    this.getBgUrl();                
                    this.notification("Success", "");                  
                    this.clearUploadedImage();  
                  }else{  
                    axios.delete(url, { 
                      headers: {'Authorization': "Bearer " + this.system.JWT}
                    }).then(res => {
                      //预留
                    });
                    this.showCodeMsg(resData.code, this, resData.msg);         
                  }
                }.bind(this)
              );
            };
            xhr.onerror = function(e) {
              this.notification("error", e);
            };
            xhr.setRequestHeader('Authorization', 'Bearer '+ this.system.JWT)
            xhr.send(this.file);
          }else{            
            this.showCodeMsg(res.code, this, res.msg);
          }
        }.bind(this)
      );
    },
    onSaveSutitle() {
      var option = {
        enable: this.subtitle.enable,
        type: this.subtitle.type,
        fontSize: parseInt(this.subtitle.fontSize),
        foreColor: this.subtitle.foreColor,
        backColor: this.subtitle.backColor,
        content: this.subtitle.content,
        pos: this.subtitle.pos,
        base: {
          h: 100,
          v: 100
        }
      };
      
      api.onRequest(
        "$method.$set.media.mo.ch" + this.currentRow.index + ".subtitle" + this.subtitle.index,
        JSON.stringify(option),
        null,
        null,
        function(msg, reqReply) {
          var res = JSON.parse(msg)
          if(res.code ==0){            
            ebus.emit("getOutputChannelInfo", this);
            this.notification('Success','')
            this.subtitleVisible = false
          }else{
            this.showCodeMsg(res.code, this, res.msg);
          }
        }.bind(this)
      );
    },
    editSubtitle(index, row) {
      this.subtitleVisible = true;
      for(var protoName in row){
        this.subtitle[protoName] = row[protoName];
      }      
      // this.subtitle = row;      
      this.showSubContent = row.type == 'text' ? true : false;
    },
    onFileChange(file) {
      //校验是否为.jpg格式
      var arrFilename = file.name.split('.');
      var sufName = arrFilename[arrFilename.length - 1];      
      if(sufName != 'jpg'){
        this.notification('error', this.$t('message.medias.typeErr'));
        return;
      }

      this.file = file;
      file.name = 'background' + this.index +'.jpg';      
      var url;
      if (navigator.userAgent.indexOf("MSIE") >= 1) {// IE        
        url = document.getElementById("imgUploadFile").value;
      } else if (navigator.userAgent.indexOf("Firefox") > 0) {// Firefox        
        url = window.URL.createObjectURL(
          document.getElementById("imgUploadFile").files.item(0)
        );
      } else if (navigator.userAgent.indexOf("Chrome") > 0) {// Chrome        
        url = window.URL.createObjectURL(
          document.getElementById("imgUploadFile").files.item(0)
        );
      }     
      this.dialogImageUrl = url;
    },
    handlePictureCardPreview(file){
      this.dialogImageUrl = window.URL.createObjectURL(this.file); 
      this.dialogVisible = true;
    },
    onSubTypeChange(e){
      if(this.subtitle.type == 'text'){
        this.showSubContent = true;
      } else{
        this.showSubContent = false;
      }
    },
    drawLayout() {     
      var canvas = document.getElementById("myCanvas");
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "#000";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.font = this.subtitle.fontSize + 'px sans-serif';
      ctx.textBaseline = "top";
      ctx.fillStyle = this.subtitle.foreColor    
      
      var x = 0;
      if (this.subtitle.pos.x < 0) {
        var posX = 0;
        var showLen = this.subtitle.content.length * this.subtitle.fontSize / 30;
        if (showLen < 100) {
          posX = (100 - showLen) / 2;
        }
        x = canvas.width * posX / 100;
      } else {
        x = canvas.width * this.subtitle.pos.x / 100;
      }
      var y = canvas.height * this.subtitle.pos.y / 100;
      ctx.fillText('Example', x, y);
    },
    onBgEnableChanged(val){
      if(!this.defaultUrl){
        return;
      }
      var opt = {
        enable: val,
        imgFile: this.defaultUrl
      }
      api.onRequest(
        "$method.$set.media.mo.ch" + this.index + ".background",
        JSON.stringify(opt),
        null,
        null,
        function(msg2, reply) {
          var resData = JSON.parse(msg2);
          if (resData.code == 0) {
            this.notification("Success", "");
          } else {
            if(this.bgEnable){
              this.bgEnable = false;
            } else{
              this.bgEnable = true;
            }
            this.showCodeMsg(resData.code, this, resData.msg);
          }
        }.bind(this)
      );
    },
    onSubDialogOpen(){
      setTimeout(()=>{
        this.drawLayout();
      }, 200);
    },
    clearUploadedImage () {
      this.$refs.upload.clearFiles();
    },
    onFilesOutOfMax(file, fileList){
      //校验是否为.jpg格式
      var arrFilename = file[0].name.split('.');
      var sufName = arrFilename[arrFilename.length - 1];      
      if(sufName != 'jpg'){
        this.notification('error', this.$t('message.medias.typeErr'));
        return;
      }

      this.file = file[0];
      var upload = document.getElementById('imgUploadFile');     
      upload.children[0].children[0].children[0].src =  window.URL.createObjectURL(file[0]); 
    },
    showContent(row){      
      if(row.type == 'text'){
        return row.content;
      } else{
        if(row.type){
          return `{${row.type}}`;
        } else{
          return '';
        }
        
      }
    },
  }
};
</script>

<style @scoped>
.el-form-item__content select {
  height: 28px;
}
.el-slider{
  width:300px;
  margin-left: 126px;
}
</style>

